package chances.epg.ui.taglib.utils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

import com.google.common.base.Strings;

@SuppressWarnings("serial")
public class SetTag extends TagSupport {

	private static final String REQUEST = "request";
	private static final String SESSION = "session";

	@Override
	public int doEndTag() throws JspException {
		Object aValue = value;
		;
		if (aValue == null) {
			aValue = defaultValue;
		} else if (String.class.isInstance(aValue)
				&& Strings.isNullOrEmpty(value.toString())) {
			aValue = defaultValue;
		}
		if (aValue != null) {
			pageContext.setAttribute(this.var, aValue, this.scope);
		}

		init();
		return super.doEndTag();
	}

	private static final String APPLICATION = "application";

	private Object value;
	private Object defaultValue;
	private String var;
	private int scope;

	public SetTag() {
		super();
		init();
	}

	public String getVar() {
		return var;
	}

	public void setDefault(Object def) {
		this.defaultValue = def;
	}

	public void setValue(Object value) {
		this.value = value;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public void setScope(String scope) {
		this.scope = getScope(scope);
	}

	public static int getScope(String scope) {
		int ret = PageContext.PAGE_SCOPE; // default

		if (REQUEST.equalsIgnoreCase(scope))
			ret = PageContext.REQUEST_SCOPE;
		else if (SESSION.equalsIgnoreCase(scope))
			ret = PageContext.SESSION_SCOPE;
		else if (APPLICATION.equalsIgnoreCase(scope))
			ret = PageContext.APPLICATION_SCOPE;

		return ret;
	}

	private void init() {
		value = var = null;
		defaultValue = null;
		scope = PageContext.PAGE_SCOPE;
	}

	public void release() {
		super.release();
		init();
	}
}
